import config from '../config/index';
import Vue from 'vue';
// 时间戳格式化
export function timestampToTime(timestamp, type) {
  const date = new Date(timestamp); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
  const Y = `${date.getFullYear()}`;
  const M = `${date.getMonth() + 1 < 10 ? `0${date.getMonth() + 1}` : date.getMonth() + 1}`;
  const D = date.getDate() < 10 ? `0${date.getDate()}` : date.getDate();
  const h = `${date.getHours() < 10 ? `0${date.getHours()}` : date.getHours()}`;
  const m = date.getMinutes() < 10 ? `0${date.getMinutes()}` : date.getMinutes();

  if (type === 1) {
    return `${M}-${D} ${h}:${m}`;
  } else if (type === 2) {
    return Y + M + D;
  } else if (type === 3) {
    return `${Y}-${M}-${D}`;
  }
}
// 跳转到k线详情页
export function jumpTokline(stock, market) {
  if (!market) {
    Vue.prototype.$toast(`${stock}现已退市，无法查看`);
    return;
  }
  if (market && stock) {
    window.location.href = `client.html?action=ymtz^webid=2216^stockcode=${stock}^marketid=${market}`;
  }
}
//跳分时页
export function jumpToStockDetail(stockCode, marketId) {
  location.href = `client://client.html?action=ymtz^webid=2205^stockcode=${stockCode}^marketid=${marketId}`;
}
// 遮罩层禁止底部滑动
export function stopBodyScroll() {
  const bodyEl = document.body;
  const isFixed = bodyEl.style.position === '';
  if (isFixed) {
    bodyEl.setAttribute('scrollY', window.scrollY);
    bodyEl.style.top = `${-window.scrollY}px`;
    bodyEl.style.position = 'fixed';
  } else {
    bodyEl.style.position = '';
    bodyEl.style.top = '';
    const scrollY = Number(bodyEl.getAttribute('scrollY'));
    window.scrollTo(0, scrollY);
  }
}

const judgeIsNull = function (val) {
  const target = typeof val === 'object' ? Object.prototype.toString.call(val) : `${val}`;
  if (/null|undefined|nan|^\s*$/i.test(target)) {
    return '--';
  }
  return val;
};
// 空值判断
export function redgreenhandler(val) {
  if (!val || val === '--' || val === undefined) {
    return '--';
  }
  const currentNumber = val.replace('%', '');
  if (judgeIsNull(val) === '--') {
    return '--';
  }
  return parseFloat(currentNumber);
}
// 成交额转换
export function turnOverExchange(val) {
  if (!val || val === '--' || val === undefined) {
    return '--';
  }
  const currentNumber = val.replace('万', '');
  if (judgeIsNull(val) === '--') {
    return '--';
  }
  const strLen = currentNumber.split('.')[0].toString().length;
  if (strLen >= 5) {
    return `${(currentNumber / 10000).toFixed(2)}亿`;
  } else {
    return val;
  }

  // return tempValue;
}
// 比较函数
export function compare(property) {
  return function (a, b) {
    const value1 = a[property];
    const value2 = b[property];
    return value1 - value2;
  };
}
/**
 *
 * @param {股票id列表} stockIdArr
 * @param {时长id列表} marketIdArr
 * @param {要操作的数组} list
 * @param {回调} callback
 * @returns
 */
export function webHQCommon(stockIdArr, marketIdArr, list, callback) {
  disconnectWebHQ();
  //客户端协议实时获取：现价，涨跌幅
  //注册事件
  callNativeHandler('getHQ', {
    columnorder: ['10', '34818', '4', '19', '34370', '34304', '34307'], // 现价 涨跌幅 涨跌额
    stocklist: stockIdArr, //股票代码列表
    marketlist: marketIdArr, //市场id类别
  });
  //注册获取行情
  registerWebHandler('getHQ', function (data) {
    if (data.method == 'normal') {
      if (data.data) {
        data = data.data;
        if (!data) return;
        const stockNowPriceMap = {}; //现价
        const stockUpDown = {}; //涨跌幅
        const turnOver = {}; //成交额
        const largeAmount = {}; //大单净量
        const earnings = {}; //市盈率
        const totalMarketValue = {}; //总市值
        for (let index = 0; index < data['4'].length; index++) {
          // 股票id做key 涨跌幅做value 构造map
          stockNowPriceMap[data['4'][index]] = data['10'][index]; //现价
          stockUpDown[data['4'][index]] = data['34818'][index]; //涨跌幅
          turnOver[data['4'][index]] = data['19'][index]; //成交额
          largeAmount[data['4'][index]] = data['34370'][index]; //大单净量
          earnings[data['4'][index]] = data['34304'][index]; //动态市盈率
          totalMarketValue[data['4'][index]] = data['34307'][index]; //总市值
        }
        list.forEach(item => {
          item.nowPrice = stockNowPriceMap[item.stockCode] ? stockNowPriceMap[item.stockCode] : '';
          const upDownVal = redgreenhandler(stockUpDown[item.stockCode]);
          item.upDownPercent = upDownVal !== '--' ? upDownVal.toFixed(2) : upDownVal;
          // 退市股票特殊处理
          if (stockNowPriceMap[item.stockCode] === '--' && upDownVal === '--') {
            item.nowPrice = -9999;
            item.upDownPercent = -9999;
          }

          item.turnOver = turnOver[item.stockCode]
            ? turnOverExchange(turnOver[item.stockCode])
            : '';
          item.largeAmount = largeAmount[item.stockCode];
          item.earnings = redgreenhandler(earnings[item.stockCode]);
          item.totalMarketValue = totalMarketValue[item.stockCode];
        });
        callback(list);
      }
    }
  });
  return list;
}

// 断开webHQ链接
export function disconnectWebHQ(){
  callNativeHandler(
    'getHQ',
    {
      method:'disconnect',
    },
    ()=>{
      // 客户端协议
    }
  )
}
/**
 *
 * @param {要处理的对象} item
 * @param {订阅类型} pushType
 * @param {是否为备选池} isSelectType
 * @param {用来标识股池还是股票池} type
 * @returns
 */
export function apiDataDeal(item, pushType, isSelectType, type, isJTZZ) {
  if (!item || item === undefined) {
    return;
  }
  const ggzcId=2;
  const jgccId=10;
  const ybyxId=118;
  const bmltId=108;
  const xfltId=78;
  const newXfltId=178;
  const newRdldId=186;
  const newDtqsId=202;
  const xfjjId=218;
  const bdqzId=220;
  const rdjjId=222;
  const ncId=212;
  const gpcId=Number(window.getParam('gpc_id'));
  const includeGpcId = [xfltId, ggzcId, jgccId, bmltId, ybyxId, newXfltId, newRdldId, newDtqsId,xfjjId,bdqzId,rdjjId,ncId].includes(gpcId);
  // 状态字段处理
  let mapStatus = isSelectType
    ? '备选'
    // YRJ-3715 修复多头趋势和强龙低吸记录状态与PC不一致的问题，同时将所有股票池规则统一为一个
    : config.historyStatusMap[item.status];
  // 热点轮动、深一度和小盘成长状态字段处理
  if ([11, 4, 6].includes(Number(getParam('gpc_id')))) {
    if (item.amount_increase > 0) {
      mapStatus = '止盈';
    } else if (item.amount_increase < 0) {
      mapStatus = '止损';
    } else {
      mapStatus = '--';
    }
  }
  let addDateTemp = item.add_date ? item.add_date.split(' ')[0] : item.add_date;
  //价值成长
  if (getParam('gpc_id') === '734') {
    addDateTemp = item.buy_date ? item.buy_date.split(' ')[0] : item.buy_date;
  }
  // 处理强龙低吸和多头趋势股票池
  if ((window.getParam('gpc_id') === '2072' || window.getParam('gpc_id') === '202') && item.buy_tips) {
    if (item.buy_price !== undefined && String(item.buy_price) !== '0.00') {
      addDateTemp = item.buy_date ? item.buy_date.split(' ')[0] : item.buy_date;
    } else {
      addDateTemp = '--';
    }
  }
  // 二期接口字段处理
  if (!isJTZZ && !includeGpcId) {
    // 操作提醒数据
    const operaSug = [];

    operaSug['buyTips'] = item.buy_tips;
    operaSug['sellTips'] = item.sell_tips;
    operaSug['jsm'] = item.jsm;
    operaSug['jbm'] = item.jbm;
    operaSug['xxm'] = item.xxm;

    const returnData = {
      stockCode: item.stock_code,
      stockName: item.stock_name,
      id: item.id,
      market: item.market,
      nowPrice: '', //现价
      upDownPercent: '', //涨跌幅
      turnOver: '', //成交额
      largeAmount: '', //大单净量
      earnings: '',
      totalMarketValue: '',
      rangeProfit: item.amount_increase
        ? parseFloat(item.amount_increase).toFixed(2)
        : item.amount_increase || item.range_profit
        ? parseFloat(item.range_profit * 100).toFixed(2)
        : item.range_profit, //区间涨幅
      highestProfit: item.region_profit
        ? parseFloat(item.region_profit).toFixed(2)
        : item.region_profit, //最高涨幅
      buyPrice: item.add_price
        ? parseFloat(item.add_price).toFixed(2)
        : item.add_price || item.buy_price
        ? parseFloat(item.buy_price).toFixed(2)
        : item.buy_price, //入池价格
      buyDate: item.buy_date ? item.buy_date.split(' ')[0] : item.buy_date, //入池时间,
      addDate: addDateTemp,
      sellPrice: item.sell_price ? parseFloat(item.sell_price).toFixed(2) : item.sell_price, //卖出价格
      sellDate: item.sell_date ? item.sell_date.split(' ')[0] : item.sell_date, //卖出时间
      industry: item.industry, //所属行业
      position: item.position ? parseFloat(item.position).toFixed(2) : item.position, //仓位
      status: mapStatus,
      statusValue: item.status,
      buyDateSort: item.buy_date ? item.buy_date.split(' ')[0].split('-').join('') : item.buy_date,
      buySellDate: item.sell_date
        ? item.sell_date.split(' ')[0].split('-').join('')
        : item.sell_date,
      subscribeList: item.subscribeList,
      isStocks: type,
      operaSug, //操作建议
      rePrice: item.buy_price ? getRePrice(item.buy_price) : item.buy_price,
      shape: item.shape,
    };
    return returnData;
  }
  const tempData = {
    stockCode: item.stock_code,
    stockName: item.stock_name,
    gpc: item.gpc_id,
    id: item.id,
    stockId: item.stock_id,
    btnGray: true,
    pushtype: pushType,
    market: item.market,
    nowPrice: '', //现价
    upDownPercent: '', //涨跌幅
    rangeProfit: item.range_profit
      ? parseFloat(item.range_profit * 100).toFixed(2)
      : item.range_profit, //区间涨幅
    highestProfit: item.highest_profit
      ? parseFloat(item.highest_profit * 100).toFixed(2)
      : item.highest_profit, //最高涨幅
    buyPrice: item.buy_price ? parseFloat(item.buy_price).toFixed(2) : item.buy_price, //入池价格
    buyDate: item.buy_date ? item.buy_date.split(' ')[0] : item.buy_date, //入池时间,
    addDate: item.add_date ? item.add_date.split(' ')[0] : item.add_date,
    sellPrice: item.sell_price ? parseFloat(item.sell_price).toFixed(2) : item.sell_price, //卖出价格
    sellDate: item.sell_date ? item.sell_date.split(' ')[0] : item.sell_date, //卖出时间
    industry: item.industry, //所属行业
    position: item.position ? parseFloat(item.position * 100).toFixed(2) : item.position, //仓位
    status: mapStatus,
    statusValue: item.status,
    buyDateSort: item.buy_date ? item.buy_date.split(' ')[0].split('-').join('') : item.buy_date,
    buySellDate: item.sell_date ? item.sell_date.split(' ')[0].split('-').join('') : item.sell_date,
    subscribe: item.subscribe,
    subscribeList: item.subscribeList,
    isStocks: type,
    rePrice: item.buy_price ? getRePrice(item.buy_price) : item.buy_price, //买入参考价
  };
  return tempData;
}

//图线适配
export function sizeAdapter() {
  let typeSize = 'small';
  if (window.getPlatform() !== 'gphone') {
    typeSize = 'large';
  }
  return typeSize;
}
// 参考价格
export function getRePrice(val) {
  if (val === undefined) {
    return '--';
  }
  if (val === 0 || val === '0.00') {
    return '--';
  }
  const value = parseFloat(val);
  return `${(value * 0.995).toFixed(2)}-${(value * 1.005).toFixed(2)}`;
}

// 静态数据处理
export function dealStaticData(dataObj, gpcId, type) {
  const staticTempArr = [];
  if (type === 'others') {
    staticTempArr['runDate'] = dataObj.run_days; //组合运行天数
    staticTempArr['yearProft'] = dataObj.year_profit_rate / 100; //年化收益

    staticTempArr['cpDescribe'] = config.detailStocksDescribe[gpcId === 2 ? 4 : gpcId];
    staticTempArr['profit'] = dataObj.total_profit / 100; //总收益
    staticTempArr['success_rate'] = dataObj.success_rate / 100; //成功率
    staticTempArr['avg_profit'] = dataObj.profit_avg / 100; //平均止盈
    staticTempArr['avg_loss'] = dataObj.lose_avg / 100; //平均止损
    return staticTempArr;
  }
  staticTempArr['runDate'] = dataObj.run_date;
  // 股池简介
  staticTempArr['cpDescribe'] = config.detailStocksDescribe[gpcId];
  staticTempArr['holdProfit'] = dataObj.statistic.hold_profit;
  staticTempArr['yearProft'] = dataObj.statistic.year_proft;
  staticTempArr['profit'] = dataObj.statistic.profit;
  staticTempArr['maxProfit'] = dataObj.statistic.max_profit;
  staticTempArr['maxDrawdown'] = dataObj.statistic.max_drawdown;
  staticTempArr['success_rate'] = dataObj.statistic.success_rate;
  staticTempArr['avg_profit'] = dataObj.statistic.avg_profit;
  staticTempArr['avg_loss'] = dataObj.statistic.avg_loss;
  return staticTempArr;
}
// 根据传入的月数切割数组
export function spliceData(mon, arr) {
  const date = new Date();
  const timeStamp = date.setMonth(date.getMonth() - mon);
  const dateTime = timestampToTime(timeStamp, 3);
  const dateStr = dateTime.split('-').join('');
  let j = 0;
  for (let i = arr.length - 1; i >= 0; i--) {
    if (Number(arr[i].date) < dateStr) {
      j = i + 1;
      break;
    }
  }
  return arr.slice(j);
}

export function circleDate(date) {
  const circle = {
    '03': '年一季报',
    '06': '年二季报',
    '09': '年三季报',
    12: '年年报',
  };
  const dateArr = date.split('-');
  const year = dateArr[0];
  const month = dateArr[1];
  return year + circle[month];
}
// 防抖函数
export function debounce(fn, delay = 500) {
  // timer 是在闭包中的
  let timer = null;
  return function () {
    if (timer) {
      clearTimeout(timer);
    }
    timer = setTimeout(() => {
      fn.apply(this, arguments);
      timer = null;
    }, delay);
  };
}
// 节流
export function throttle(fn, delay) {
  let timer = null;

  return function () {
    if (timer) {
      return;
    }
    timer = setTimeout(() => {
      fn.apply(this, arguments);
      timer = null;
    });
  };
}
